import React, { useState, useEffect, useRef } from 'react';
// import { useNavigate } from 'react-router-dom';
import styles from './ke.module.css';
// import { SendOutlined, UserOutlined, CustomerServiceOutlined, SettingOutlined, CloseOutlined, LoadingOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { SendOutlined, UserOutlined, CustomerServiceOutlined, SettingOutlined, CloseOutlined, LoadingOutlined, ArrowLeftOutlined } from '@ant-design/icons';

const Ke = () => {
  const navigate = useNavigate();
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [userId, setUserId] = useState(null);
  const [userType, setUserType] = useState('customer');
  const [connected, setConnected] = useState(false);
  const [showSettings, setShowSettings] = useState(false);
  const [error, setError] = useState(null);
  const [connecting, setConnecting] = useState(false);
  const wsRef = useRef(null);
  const chatAreaRef = useRef(null);
  const messageEndRef = useRef(null);
  const reconnectTimeoutRef = useRef(null);

  // 聊天区域自动滚动到底部 - 只在消息更新时滚动
  const prevMessagesLengthRef = useRef(0);

  const router=useNavigate()
  
  useEffect(() => {
    // 只有消息数量增加时才滚动
    if (messages.length > prevMessagesLengthRef.current && messageEndRef.current) {
      messageEndRef.current.scrollIntoView({ behavior: 'smooth' });
      prevMessagesLengthRef.current = messages.length;
    }
  }, [messages]);

  // 建立WebSocket连接
  useEffect(() => {
    // 清除之前的重连定时器
    if (reconnectTimeoutRef.current) {
      clearTimeout(reconnectTimeoutRef.current);
    }

    const connectWebSocket = () => {
      try {
        console.log('尝试连接WebSocket...');
        setConnecting(true);
        // 尝试直接连接到本地WebSocket服务器
        const ws = new WebSocket('ws://192.168.79.208:8080');
        wsRef.current = ws;

        ws.onopen = () => {
          console.log('WebSocket连接已建立');
          setConnected(true);
          setConnecting(false);
          setError(null);
          
          // 如果已有userType但不是默认的，立即发送设置用户类型请求
          if (userType !== 'customer' && ws.readyState === 1) {
            console.log('发送用户类型设置:', userType);
            ws.send(JSON.stringify({
              type: 'setUserType',
              userType: userType
            }));
          }
        };

        ws.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data);
            console.log('收到消息:', data);
            
            switch (data.type) {
              case 'register':
                setUserId(data.userId);
                // 不要覆盖已有的用户类型
                if (!userId) {
                  setUserType(data.userType);
                }
                break;
              
              case 'history':
                if (Array.isArray(data.messages)) {
                  // 直接设置历史消息而不是追加
                  setMessages(data.messages);
                } else {
                  console.error('收到的历史消息不是数组:', data.messages);
                }
                break;
              
              case 'message':
                // 使用去重函数处理新消息
                processNewMessage(data);
                break;
              
              default:
                console.log('未知消息类型:', data);
            }
          } catch (error) {
            console.error('处理消息错误:', error);
          }
        };

        ws.onclose = (event) => {
          console.log(`WebSocket连接已关闭，代码: ${event.code}, 原因: ${event.reason}`);
          setConnected(false);
          setConnecting(true);
          
          // 尝试重新连接
          reconnectTimeoutRef.current = setTimeout(() => {
            console.log('尝试重新连接...');
            connectWebSocket();
          }, 3000);
        };

        ws.onerror = (error) => {
          console.error('WebSocket错误:', error);
          setConnected(false);
          setConnecting(false);
          setError('连接服务器失败，请检查服务器是否启动');
        };

        // 发送心跳包
        const heartbeatInterval = setInterval(() => {
          if (ws.readyState === 1) { // 1 = OPEN
            ws.send(JSON.stringify({ type: 'pong' }));
          }
        }, 25000);

        return () => {
          console.log('清理WebSocket连接...');
          clearInterval(heartbeatInterval);
          if (ws && ws.readyState <= 1) { // 0 = CONNECTING, 1 = OPEN
            ws.close();
          }
        };
      } catch (err) {
        console.error('连接WebSocket时出错:', err);
        setConnected(false);
        setConnecting(false);
        setError(`连接错误: ${err.message}`);
        
        // 尝试重新连接
        reconnectTimeoutRef.current = setTimeout(connectWebSocket, 5000);
      }
    };

    connectWebSocket();

    // 组件卸载时清理
    return () => {
      if (reconnectTimeoutRef.current) {
        clearTimeout(reconnectTimeoutRef.current);
      }
      
      if (wsRef.current) {
        try {
          wsRef.current.close();
        } catch (e) {
          console.error('关闭WebSocket时出错:', e);
        }
      }
    };
  }, []); // 仅在组件挂载时执行一次

  // 切换用户类型（客户/客服）
  const toggleUserType = () => {
    const newUserType = userType === 'customer' ? 'service' : 'customer';
    console.log(`切换用户类型: ${userType} -> ${newUserType}`);
    
    // 先更新状态，再发送请求
    setUserType(newUserType);
    
    if (wsRef.current && wsRef.current.readyState === 1) { // 1 = OPEN
      console.log('发送用户类型设置请求');
      wsRef.current.send(JSON.stringify({
        type: 'setUserType',
        userType: newUserType
      }));
    } else {
      console.warn('WebSocket未连接，无法发送用户类型设置请求');
    }
    
    setShowSettings(false);
  };

  // 发送消息
  const sendMessage = () => {
    if (!inputValue.trim() || !wsRef.current || wsRef.current.readyState !== 1) {
      console.warn('无法发送消息:', !inputValue.trim() ? '消息为空' : 'WebSocket未连接');
      return;
    }
    
    try {
      console.log(`发送消息: ${inputValue.trim()}, 用户类型: ${userType}`);
      
      // 创建消息对象
      const messageData = {
        type: 'message',
        message: inputValue.trim()
      };
      
      // 发送到服务器
      wsRef.current.send(JSON.stringify(messageData));
      
      // 本地添加消息用于即时显示
      const localMessage = {
        type: 'message',
        fromUserId: userId,
        fromUserType: userType,
        message: inputValue.trim(),
        timestamp: new Date().toISOString(),
        isLocal: true // 标记为本地消息
      };
      
      // 使用去重函数处理本地消息
      processNewMessage(localMessage);
      
      // 清空输入
      setInputValue('');
    } catch (err) {
      console.error('发送消息时出错:', err);
      setError(`发送失败: ${err.message}`);
    }
  };

  // 处理Enter键发送消息
  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      sendMessage();
    }
  };

  // 格式化时间显示
  const formatTime = (timeString) => {
    if (!timeString) return new Date().toLocaleTimeString();
    
    try {
      // 尝试解析ISO日期或本地时间字符串
      const date = new Date(timeString);
      
      // 检查是否为有效日期
      if (isNaN(date.getTime())) {
        return timeString; // 如果无法解析，则返回原始字符串
      }
      
      // 格式化时间: HH:MM
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${hours}:${minutes}`;
    } catch (e) {
      console.error('时间格式化错误:', e);
      return timeString;
    }
  };

  // 处理收到新消息时的去重逻辑
  const processNewMessage = (newMessage) => {
    setMessages(prevMessages => {
      // 如果新消息已在消息列表中，则不添加
      const exists = prevMessages.some(msg => 
        msg.fromUserId === newMessage.fromUserId && 
        msg.message === newMessage.message && 
        msg.timestamp === newMessage.timestamp
      );
      
      if (exists) {
        return prevMessages;
      }
      
      // 如果是服务器确认消息，移除对应的本地消息
      if (!newMessage.isLocal) {
        const filteredMessages = prevMessages.filter(msg => 
          !(msg.isLocal && 
            msg.fromUserId === newMessage.fromUserId && 
            msg.message === newMessage.message)
        );
        return [...filteredMessages, newMessage];
      }
      
      return [...prevMessages, newMessage];
    });
  };

  return (
    <div className={styles.container}>
      <div className={styles.chatContainer}>
        <div className={styles.header}>
          <div className={styles.headerTitle}>
           
  
            <button className={styles.backButton} onClick={() => navigate('/tabber/first')}>
              <ArrowLeftOutlined />
            </button>
            <span className={styles.logo}>客服系统</span>
            <div className={styles.status}>
              <span 
                className={styles.statusIndicator} 
                style={{ background: connected ? '#52c41a' : connecting ? '#faad14' : '#f5222d' }}
              />
              <span className={styles.statusText}>
                {connected ? '在线' : connecting ? '连接中...' : '离线'}
              </span>
              <span className={styles.userRole}>
                {userType === 'customer' ? '客户模式' : '客服模式'}
              </span>
              {userId && <span className={styles.userId}>ID: {userId}</span>}
            </div>
          </div>
          <div className={styles.headerActions}>
            <SettingOutlined 
              className={styles.settingsIcon} 
              onClick={() => setShowSettings(!showSettings)}
            />
          </div>
          
          {showSettings && (
            <div className={styles.settingsPanel}>
              <div className={styles.settingsHeader}>
                <span>设置</span>
                <CloseOutlined onClick={() => setShowSettings(false)} />
              </div>
              <div className={styles.settingsContent}>
                <div className={styles.settingItem}>
                  <span>当前身份:</span>
                  <span>{userType === 'customer' ? '客户' : '客服'}</span>
                </div>
                <div className={styles.settingItem}>
                  <span>用户ID:</span>
                  <span className={styles.idValue}>{userId || '未分配'}</span>
                </div>
                <div className={styles.settingItem}>
                  <span>连接状态:</span>
                  <span>{connected ? '已连接' : connecting ? '连接中' : '未连接'}</span>
                </div>
                <button 
                  className={styles.roleToggleButton}
                  onClick={toggleUserType}
                  disabled={!connected}
                >
                  切换为{userType === 'customer' ? '客服' : '客户'}
                </button>
                {error && <div className={styles.errorMessage}>{error}</div>}
              </div>
            </div>
          )}
        </div>
        
        <div className={styles.chatArea} ref={chatAreaRef}>
          {error && <div className={styles.errorNotice}>{error}</div>}
          
          {messages.length === 0 ? (
            <div className={styles.welcomeMessage}>
              <div className={styles.welcomeIcon}>
                {userType === 'customer' ? <CustomerServiceOutlined /> : <UserOutlined />}
              </div>
              <p>欢迎使用在线客服系统，{userType === 'customer' ? '有什么可以帮助您的？' : '请等待客户咨询。'}</p>
              {!connected && (
                <p className={styles.connectingMessage}>
                  {connecting ? (
                    <>
                      <LoadingOutlined spin className={styles.loadingIcon} /> 正在连接服务器...
                    </>
                  ) : '服务器连接失败'}
                </p>
              )}
            </div>
          ) : (
            messages.map((msg, index) => (
              <div 
                key={index} 
                className={`${styles.messageWrapper} ${msg.fromUserType === userType ? styles.myMessage : styles.otherMessage} ${msg.isLocal ? styles.localMessage : ''}`}
              >
                <div className={styles.messageInfo}>
                  <span className={styles.messageUser}>
                    {msg.fromUserType === 'customer' ? '客户' : '客服'}
                    {msg.fromUserId && <span className={styles.messageUserId}> ({msg.fromUserId})</span>}
                  </span>
                  <span className={styles.messageTime}>
                    {formatTime(msg.timestamp)}
                  </span>
                </div>
                <div className={styles.messageBubble}>
                  {msg.message}
                </div>
              </div>
            ))
          )}
          <div ref={messageEndRef}></div>
        </div>

        <div className={styles.inputArea}>
          <input 
            type="text" 
            value={inputValue} 
            onChange={e => setInputValue(e.target.value)} 
            onKeyPress={handleKeyPress}
            placeholder={connected ? "请输入消息..." : connecting ? "正在连接服务器..." : "服务器未连接"}
            disabled={!connected}
            className={styles.messageInput}
          />
          <button 
            className={styles.sendButton}
            onClick={sendMessage} 
            disabled={!connected || !inputValue.trim()}
          >
            <SendOutlined />
          </button>
        </div>
      </div>
    </div>
  );
};

export default Ke;